var json_answer={};
var timestamp;
$(function(){
	initOptions();
	});
function initOptions(){
	$('.skin-minimal input').iCheck({
		checkboxClass: 'icheckbox-blue',
		radioClass: 'iradio-blue',
		increaseArea: '20%'
	})
}
$(function(){
	var scale_id=($.cookie("scale_id"));
	var url="./InitTestpage";
	$.ajax({
		"data":"scale_id="+scale_id,
		"url":url,
		"type":"POST",
		"success":function(result){
			initPage(result);
			initQuestion_btn();
		},
		"error":function(result){
			alert('请求超时!');
		}
	});
});
/* 题目按钮初始化 */
function initQuestion_btn(){
	/* 左侧题目导航栏按钮 */
	$('#menu-member').find('ul').on('click',function(){
		writeAnswer();
		var grade=$(this).find('a').attr('name');
		showQuestion(grade);
	})
	/* 上一题按钮 */
	$('.content-foot').find('a').eq(0).on('click',function(){
		var grade="q"+(Number($('#title').html().substr(2))-1);
		writeAnswer();
		showQuestion(grade);
	})
	/* 下一题按钮 */
	$('.content-foot').find('a').eq(1).on('click',function(){
		var grade="q"+(Number($('#title').html().substr(2))+1);
		writeAnswer();
		showQuestion(grade);
	})
	$('.content-foot').find('a').eq(2).on('click',function(){
		submitbtn();
	})
	$('.mybtn').on('click',function(){
		location.href='./student/main.jsp';
	})
}
function initPage(result){
	var json=JSON.parse(result);
	var scale_info=json.scale_info;
	/* console.log("scale_id"+scale_info.scale_id);
	console.log("type"+scale_info.type);
	console.log("name"+scale_info.name);
	console.log("test_time"+scale_info.test_time); */
	$('.logo').html(scale_info.type).attr(scale_info.type);
	$('.scale_name').html(scale_info.name);
	$('.time').html(scale_info.test_time);
	/*设置时间*/
	timestamp=Date.parse(new Date("2000-10-10 "+scale_info.test_time));
	initTimer();
	var questions=json.questions;
	var text;
	for(var num in questions){
		/* 获取每一题的信息 */
		question_info=questions[num];
		question_id=question_info.question_id;
		question=question_info.question;
		options=question_info.options;
		question_type=question_info.question_type;
		reference_score=question_info.reference_score;
		/* 将题目信息存入本地 */
		var grade="q"+(Number(num)+1);
		sessionStorage.setItem(grade,JSON.stringify(question_info));
		/* 添加题目导航栏题目按钮 */
		text="<ul><li><a name='"+grade+"' href='javascript:void(0)'>题目"+(Number(num)+1)+" "+question_type+"<i class='flag-i'></i><br><small>"+question.substr(0,15)+"...</small></a></li></ul>"
		$('#menu-member').append(text);
		/* console.log("question_id:"+question_id);
		console.log("question:"+question);
		console.log("options:"+options);
		console.log("reference_score:"+referpnce_score); */
	}
	/* 显示第一题 */
	sessionStorage.setItem("answer", JSON.stringify(json_answer));
	showQuestion("q1");
}
function showQuestion(grade){
	var grade_num=grade.substr(1);
	if(grade_num==1) $('.content-foot').find('a').eq(0).hide();
	else $('.content-foot').find('a').eq(0).show();
	if(grade_num>=$('#menu-member').find('ul').length) $('.content-foot').find('a').eq(1).hide();
	else $('.content-foot').find('a').eq(1).show();
	$('#title').html("题目"+grade_num);
	var question_info=sessionStorage.getItem(grade);
	var json_q=JSON.parse(question_info);
	question_id=json_q.question_id;
	question=json_q.question;
	question_type=json_q.question_type;
	options=json_q.options;
	reference_score=json_q.reference_score;
	$('#question_type').html(question_type);
	$('#reference_score').html(reference_score+"分");
	$('.question').find('strong').html(question);
	$('.skin-minimal').html('');
	if(question_type=="单选题")
	for(var i in options){
		var answerText="<div class='radio-box'><input type='radio' id='r"+grade+i+"' name='option' value='"+i+"'><label for='r"+grade+i+"'>"+i+"<p>"+options[i]+"</p></label></div><br>";
		$('.skin-minimal').append(answerText);
	}
	if(question_type=="多选题")
		for(var i in options){
			var answerText="<div class='check-box'><input type='checkbox' id='c"+grade+i+"' name='option' value='"+i+"'><label for='c"+grade+i+"'>"+i+"<p>"+options[i]+"</p></label></div><br>";
			$('.skin-minimal').append(answerText);
		}
	initOptions();
	answerlist=JSON.parse(sessionStorage.getItem("answer"));
	if(answerlist[grade]){
		for(var i in answerlist[grade]){
			$('.skin-minimal').find('input').each(function(){
				if($(this).attr('value')==answerlist[grade][i]) $(this).next().trigger('click');
			})
		}
	}
}
/*提交按钮*/
function submitbtn(){
	writeAnswer();
	var answers=JSON.parse(sessionStorage.getItem("answer"));
	var answer_num=0;
	var stu_answer={};
	for(var i in answers){
		if(answers[i]) {
			var question_id=JSON.parse(sessionStorage.getItem(i))["question_id"];
			stu_answer[question_id]=answers[i];
			answer_num=answer_num+1;
		}
	}
	if(confirm("已经完成"+answer_num+"题，是否交卷？")){
		$.post('./GetAnswerServlet',"stu_answer="+JSON.stringify(stu_answer),function(result){
			var rightAnswer=JSON.parse(result);
			showResult(rightAnswer,stu_answer);
		})
	}
}

/*将答案写入本地*/
/*格式：{"q1":"A","q2":"B",...}*/
/*获取radio值：$('form')[0].radio1.value*/
function writeAnswer(){
	var answer=[];
	var grade="q"+($('#title').html().substr(2));
	if($('#question_type').html()=='单选题'){
		if($('form')[0].option.value)
		answer.push($('form')[0].option.value);
	}
	if($('#question_type').html()=='多选题'){
		$('.skin-minimal').find('.checked').find('input').each(function(){
			answer.push($(this).attr('value'));
		})
	}
	if(answer.length>0){
		$('#menu-member').find('[name='+grade+']').find('i').addClass('background_blue');
		json_answer[grade]=answer;
		sessionStorage.setItem("answer", JSON.stringify(json_answer));
	}else $('#menu-member').find('[name='+grade+']').find('i').removeClass('background_blue');

	
}
function showResult(rightAnswer,stu_answer){
	var show1;
	var show2="<span class='wrong'>?</span>";
	var flag='wrong';
	var score=0;
	for(var i in rightAnswer){
		show1="<span class='standard'>"+rightAnswer[i]+"</span>";
		$('.right_answer').append(show1);
		if(stu_answer[i]){
			if(rightAnswer[i].length==stu_answer[i].length){
				for(var j in rightAnswer[i]){
					for(var a in stu_answer[i]){
						if(stu_answer[i][a]==rightAnswer[i][j]){
							flag='right';
							break;
						}else flag='wrong';
					}
				}
			}else flag="wrong";
			show2="<span class='"+flag+"'>"+stu_answer[i]+"</span>";
			$('.stu_answer').append(show2);
		}else {
			show2="<span class='wrong'>?</span>";
			$('.stu_answer').append(show2);
		}
		if(flag=='right'){
			
			var storage=JSON.parse(sessionStorage.getItem("answer"));
			var addscore=0;
			for(var b in storage){
				addscore=Number(JSON.parse(sessionStorage.getItem(b))["reference_score"]);
			}
			score=score+addscore;
		}
		flag="wrong";
	}
	$('.result_line2').html('得分：'+score+'分');
	$('.result').removeClass('hidden');
	
}
//每20秒执行，最多5次，并命名计时器名称为B
/*$('body').everyTime('2das','B',function(){

	//do something...

	},5);*/
function initTimer(){
	self.setInterval("clock()",1000);
	/*$('body').everyTime('1s',function(){
		timestamp=timestamp-1000;
		var new_time=new Date(timestamp).getTime();
		$('.time').html(new_time);
	});*/
}
function clock(){
	timestamp=timestamp-1000;
	var new_datetime=new Date(timestamp);
	var new_time=new_datetime.toLocaleTimeString();
	if(new_datetime.getHours()==0){
		$('.time').html("00"+new_time.substr(4));
	}else{
		$('.time').html(new_time.substr(2));		
	}
	if($('.time').html()=='00:00:00'){
		writeAnswer();
		var answers=JSON.parse(sessionStorage.getItem("answer"));
		var answer_num=0;
		var stu_answer={};
		for(var i in answers){
			if(answers[i]) {
				var question_id=JSON.parse(sessionStorage.getItem(i))["question_id"];
				stu_answer[question_id]=answers[i];
				answer_num=answer_num+1;
			}
		}
		alert('考试时间到！请停止做题。');
		$.post('./GetAnswerServlet',"stu_answer="+JSON.stringify(stu_answer),function(result){
			var rightAnswer=JSON.parse(result);
			showResult(rightAnswer,stu_answer);
		})
	}
}